﻿using ShuttleBus.AdminMessages;
using ShuttleBus.Serialization;

namespace ShuttleBus.Transports.Msmq
{
    public class MsmqTransport : Transport
    {
        private readonly ICreateStreams _streamFactory;
        private readonly IReadStreams _streamReader;

        public MsmqTransport(IEndpoint endpoint, ISerializer serializer, int threadCount, ICreateStreams streamFactory, IReadStreams streamReader, int maxRetries)
            : base(endpoint, serializer, threadCount, maxRetries)
        {
            _streamFactory = streamFactory;
            _streamReader = streamReader;
        }

        public override void Send(TransportMessage message, Subscription subscription)
        {
            if (message != null && subscription != null)
            {
                var queue = Endpoint.Initialize(QueueMode.Send);
                using (var stream = _streamFactory.Create())
                {
                    Serializer.Serialize(stream, message);
                    var serializedMessage = _streamReader.ReadAll(stream);
                    queue.Send(serializedMessage, subscription.Location);
                }
            }
        }
    }
}
